package com.ewing.busi.api.pay.action;

import javax.annotation.Resource;

import org.apache.log4j.Logger;

import com.ewing.busi.api.pay.dto.JsApiPayParam;
import com.ewing.busi.api.pay.dto.WxPayReq;
import com.ewing.busi.api.pay.service.WxPayNotifyService;
import com.ewing.busi.api.pay.service.WxPayService;
import com.ewing.common.exception.BusinessException;
import com.ewing.core.app.action.base.BaseAction;
import com.ewing.core.wxpaysdk.api.paycallback.vo.PayNotifyCallBackReqParam;
import com.ewing.core.wxpaysdk.api.paycallback.vo.PayNotifyCallBackResDto;
import com.ewing.core.wxpaysdk.protocol.XmlMsgHelper;
import com.ewing.utils.JsonUtils;
import com.ewing.utils.MapUtils;

public class WxPayAction extends BaseAction {
  /**
   * 
   * created by Joeson on 2016年6月19日 下午6:14:10
   */
  private static final long serialVersionUID = -5092741742765719717L;

  /**
   * 默认生成的该类的LOG记录器，使用slf4j组件。避免产生编译警告，使用protected修饰符。
   */
  private static Logger logger = Logger.getLogger(WxPayAction.class);

  @Resource
  private WxPayService wxPayService;

  @Resource
  private WxPayNotifyService wxPayNotifyService;

  /**
   * 获取prePareId
   * 
   * @author Joeson
   */
  public void getPrepareId() {
    try {
      WxPayReq req = getParamJson(WxPayReq.class);
      checkRequired(req, "支付入参不能为空");
      logger.info(JsonUtils.toJson(req));

      JsApiPayParam param = wxPayService.pay(getLoginCusId(), req.getOrderId(), req.getIp());
      logger.info(JsonUtils.toJson(param));
      if (null != param) {
        outSucResult(param);
      } else {
        outAlert("支付初始化异常");
      }
    } catch (BusinessException e) {
      outAlert(e.getMessage());
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      outAlert("支付初始化异常");
    }

  }

  /**
   * 支付回调通知
   * 
   * @param reqParam
   * @author Joeson
   */
  public void payResultNotify() {
    PayNotifyCallBackReqParam reqParam = null;

    boolean result = false;
    try {
      reqParam = getXmlParam(PayNotifyCallBackReqParam.class);
      if (null == reqParam) {
        outTextResult(XmlMsgHelper.map2Xml(
            MapUtils.toMap(PayNotifyCallBackResDto.error("传参为空"), PayNotifyCallBackResDto.class)));
      }

      logger.info(JsonUtils.toJson(reqParam));
      result = wxPayNotifyService.payNotify(reqParam);
      logger.info("" + result);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      outTextResult(XmlMsgHelper.map2Xml(
          MapUtils.toMap(PayNotifyCallBackResDto.error("内部异常"), PayNotifyCallBackResDto.class)));
    }

    if (result) {
      outTextResult(XmlMsgHelper
          .map2Xml(MapUtils.toMap(PayNotifyCallBackResDto.suc(), PayNotifyCallBackResDto.class)));
    } else {
      outTextResult(XmlMsgHelper.map2Xml(
          MapUtils.toMap(PayNotifyCallBackResDto.error("内部异常"), PayNotifyCallBackResDto.class)));
    }
  }
}
